package com.simple.json.clazz.basic;

import java.lang.reflect.Field;

import org.json.JSONArray;
import org.json.JSONObject;

import com.simple.json.Util;
import com.simple.json.clazz.ClassInterface;

public class StringClass implements ClassInterface {

	private StringClass() {
	}

	private final static StringClass instance = new StringClass();

	public static StringClass getInstance() {
		return instance;
	}

	private String getValue(Object value) {
		if (value == null || value == JSONObject.NULL) {
			return null;
		}

		if (value instanceof JSONObject) {
			Util.logerr("expect string , but actually JSONObeject");
		} else if (value instanceof JSONArray) {
			Util.logerr("expect string , but actually JSONArray");
		}

		return value + "";
	}

	@Override
	public Class<?> getProcessClassType() {
		return String.class;
	}

	@Override
	public <T> boolean setRightValueToField(T targetObject, Field targetField,
			JSONObject jsonObject) {
		Class<?> fieldClass = targetField.getType();
		if (!fieldClass.getName().equals(getProcessClassType().getName())) {
			return false;
		}

		try {
			Object value = jsonObject.opt(targetField.getName());
//			targetField.setAccessible(true);
			String stringValue = getValue(value);
			targetField.set(targetObject, stringValue);

			Util.logout("set " + targetField.getName() + "'s String value = " + stringValue);
			return true;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public Object getRightValue(Object value) {
		return getValue(value);
	}

}
